using System;
using UnityEngine;
using QFramework;
using UnityEngine.EventSystems;

namespace ProjectMyFarmAndShe
{
	public partial class ToolbarItemTemplate : ViewController,IController
	{
		private ToolbarData mData;
		private ItemData mItemData;
		public ItemData ItemData => mItemData;
		public int Shortcut = 0;
		
		void Start()
		{
			// Code Here
		}

		public void Init(ToolbarData data,int shortcut)
		{
			mData = data;
			Shortcut = shortcut;
			ShortuctText.text = Shortcut.ToString();
			
			mData.Count.RegisterWithInitValue(count =>
				{
					if (count == 0)
					{
						Icon.Hide();
						CountText.Hide();

						if (Global.Tool != null && Global.Tool == mItemData.Tool)
						{
							CancelToolSelect();
						}
					}
					else
					{
						mItemData = this.GetSystem<IToolbarSystem>().GetItemDataByKey(mData.Key);
						Icon.Show();
						Icon.sprite = ResController.Default.GetToolIconGetKey(mItemData.Icon);
						CountText.Show();
						CountText.text = mData.Count.ToString();

						if (mItemData.Tool != null && mItemData.Tool.Type != ToolType.Speed)
						{
							CountText.Hide();
						}
					}
				})
				.UnRegisterWhenGameObjectDestroyed(gameObject);
		}

		void CancelToolSelect()
		{
			Global.Tool = null;
			Global.OnToolChange.Trigger(Global.Tool);
		}

		private void Update()
		{
			if (Input.GetKeyDown($"{Shortcut}"))
			{
				if (mData.Count.Value != 0)
				{
					if (mItemData.Tool != null)
					{
						Global.Tool = mItemData.Tool;
						Global.OnToolChange.Trigger(Global.Tool);
					}
					else
					{
						CancelToolSelect();
					}
					
				}
				else
				{
					CancelToolSelect();
				}

				var itemRect = transform.GetComponent<RectTransform>();
				var selectHighLightRect = SelectHightLight.Default.GetComponent<RectTransform>();
				selectHighLightRect.localPosition =
					itemRect.localPosition;
				selectHighLightRect.anchoredPosition =
					new Vector2(selectHighLightRect.anchoredPosition.x, -995);
			}
			
		}
		

		public IArchitecture GetArchitecture()
		{
			return Global.Interface;
		}
	}
}
